package com.moss.web;

import com.github.pagehelper.PageInfo;
import com.moss.common.core.BaseController;
import com.moss.common.domain.AjaxResult;
import com.moss.common.entity.SysCheckEntity;
import com.moss.common.exception.ServiceException;
import com.moss.common.util.IncrCounter;
import com.moss.common.vo.check.SysCheck;
import com.moss.system.service.CheckOrgService;
import com.moss.system.service.CheckService;
import com.moss.system.service.SampleService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/check")
public class CheckController extends BaseController {

    @Resource
    IncrCounter incrCounter;

    @Resource
    CheckService checkService;

    @Resource
    CheckOrgService checkOrgService;

    @Resource
    SampleService sampleService;

    @GetMapping("/randomCheckBatchNo")
    public AjaxResult<String> randomCheckBatchNo(){
        return AjaxResult.success(incrCounter.randomCheckBatchNo());
    }


    @PostMapping
    public AjaxResult<Void> check(@RequestBody @Validated SysCheckEntity check){
        if (sampleService.getSample(check.getSampleId()).getStatus() == 1){
            throw new ServiceException("当前采样已录入检测，不允许重复录入");
        }
        if (!checkOrgService.checkOrgNameAndCodeEq(check.getCheckOrgName(),check.getCheckOrgCode())){
            throw new ServiceException("检测机构名称和编码不匹配");
        }
        check.setCreateBy(getUserId());
        checkService.saveCheck(check);
        return AjaxResult.success();
    }

    @GetMapping("/{sampleId}")
    public AjaxResult<SysCheckEntity> getCheck(@PathVariable String sampleId){
        return AjaxResult.success(checkService.getCheck(sampleId));
    }


    @GetMapping("/list")
    public AjaxResult<List<SysCheck>> checkList(SysCheckEntity check){
        startPage();
        List<SysCheck> list = checkService.checkList(check);
        return AjaxResult.success(list,new PageInfo<>(list).getTotal());
    }
}
